﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.Organizations;
using YAPACS.RisServer.Abstractions;
using YAPACS.RisServer.Services.Dtos;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Controllers;
[Authorize]
public class ReportController(IReportService reportService,
                              IRepository<Report, Guid> reportRepository, 
                              IRepository<ReportImageQuality,Guid> imageQualityRepository,
                              ICurrentUserOrganization currentUserOrganization) : AbpControllerBase
{
    private readonly IReportService _reportService = reportService;
    private readonly IRepository<Report, Guid> _reportRepository = reportRepository;
    private readonly IRepository<ReportImageQuality, Guid> _imageQualityRepository = imageQualityRepository;
    private readonly ICurrentUserOrganization _currentUserOrganization = currentUserOrganization;

    [HttpGet("api/report/get-advanced-search-view")]
    public async Task<IActionResult> GetAdvancedSearchView()
    {
        var result = await _reportService.GetAdvancedSearchViewAsync();
        return Ok(result);
    }
    [HttpPost("api/report/get-list")]
    public async Task<IActionResult> GetExamListByFilter([FromBody] DataGridRequest request)
    {
        var result = await _reportService.GetExamListByFilterAsync(request);
        return Ok(result);
    }
    [HttpGet("api/report/write/{examId}")]
    public async Task<IActionResult> WriteReport(Guid examId)
    {
        var result = await _reportService.WriteReportAsync(examId);
        return Ok(result);
    }
    [HttpGet("api/report/get-exam/{reportId}")]
    public async Task<IActionResult> GetExam(Guid reportId)
    {
        var result = await _reportService.GetExamAsync(reportId);
        return Ok(result);
    }
    [HttpGet("api/report/getview/{reportId}")]
    public async Task<ActionResult> GetExamView(Guid reportId)
    {
        var result = await _reportService.GetExamViewAsync(reportId);
        return Ok(result);
    }
    [HttpPost("api/report/save")]
    public async Task<IActionResult> SaveReport(ReportDto reportDto)
    {
        var result = await _reportService.SaveReportAsync(reportDto);
        return Ok(result);
    }
    [HttpPost("api/report/submit")]
    public async Task<IActionResult> SubmitReport(Guid reportId, Guid? auditUserId, bool complete)
    {
        var result = await _reportService.SubmitReportAsync(reportId, auditUserId, complete);
        return Ok(result);
    }
    [HttpPost("api/report/revoke/{examId}")]
    public async Task<IActionResult> RevokeReport(Guid examId, [FromForm] Guid reviseType, [FromForm] string reason)
    {
        var result = await _reportService.RevokeReportAsync(examId, reviseType, reason);
        return Ok(result);
    }
    [HttpPost("api/report/amend/{examId}")]
    public async Task<IActionResult> AmendReport(Guid examId, [FromForm] Guid reviseType, [FromForm] string reason)
    {
        var result = await _reportService.AmendReportAsync(examId, reviseType, reason);
        return Ok(result);
    }
    [HttpPost("api/report/reject/{examId}")]
    public async Task<IActionResult> RejectReport(Guid examId, [FromForm] Guid reviseType, [FromForm] string reason)
    {
        var result = await _reportService.RejectReportAsync(examId, reviseType, reason);
        return Ok(result);
    }
    [HttpGet("api/report/audit/{reportId}")]
    public async Task<IActionResult> AuditReport(Guid reportId)
    {
        var result = await _reportService.AuditReportAsync(reportId);
        return Ok(result);
    }
    [HttpGet("api/report/mark-follow-up/{reportId}")]
    public async Task<IActionResult> MarkFollowUp(Guid reportId)
    {
        var result = await _reportService.MarkFollowUpAsync(reportId);
        return Ok(result);
    }
    [HttpPost("api/report/get-follow-up-record")]
    public async Task<IActionResult> GetFollowUpRecord([FromBody] Input input)
    {
        var result = await _reportService.GetFollowUpRecordAsync(input.ReportId);
        return Ok(result);
    }
    [HttpPost("api/report/revisit")]
    public async Task<IActionResult> Revisit([FromBody] Input input)
    {
        var result = await _reportService.RevisitAsync(input.ReportId);
        return Ok(result);
    }
    [HttpGet("api/report/get-e-apply/{examId}")]
    public async Task<IActionResult> GetEApply(Guid examId)
    {
        var result = await _reportService.GetEApplyAsync(examId);
        return Ok(result);
    }
    [HttpGet("api/report/get-e-medical/{examId}")]
    public async Task<IActionResult> GetEMedical(Guid examId)
    {
        var result = await _reportService.GetEMedicalAsync(examId);
        return Ok(result);
    }
    [HttpPost("api/report/get-critical-value/{examId}")]
    public async Task<IActionResult> GetCriticalValue(Guid examId)
    {
        var result = await _reportService.GetCriticalValueAsync(examId);
        return Ok(result);
    }
    [HttpPost("api/report/get-collection-menu")]
    public async Task<IActionResult> GetCollectionMenu(List<Guid> examIds, bool collect)
    {
        var result = await _reportService.GetCollectionMenuAsync(examIds, collect);
        return Ok(result);
    }
    [HttpPost("api/report/collect")]
    public async Task<IActionResult> Collect(List<Guid> examIds, List<Guid> menuIds)
    {
        var result = await _reportService.CollectAsync(examIds, menuIds);
        return Ok(result);
    }
    [HttpPost("api/report/cancel-collect")]
    public async Task<IActionResult> CancelCollect(List<Guid> examIds, List<Guid> menuIds)
    {
        var result = await _reportService.CancelCollectAsync(examIds, menuIds);
        return Ok(result);
    }
    [HttpGet("api/report/image-assessment/{examId}")]
    public async Task<IActionResult> ImageAssessment(Guid examId)
    {
        var result = await _reportService.ImageAssessmentAsync(examId);
        return Ok(result);
    }
    [HttpGet("api/report/score/{examId}")]
    public async Task<IActionResult> Score(Guid examId)
    {
        var result = await _reportService.ScoreAsync(examId);
        return Ok(result);
    }
    [HttpPut("api/report/{reportId}/update-report-style")]
    public async Task<IActionResult> UpdateExamReportStyle([FromRoute] Guid reportId, [FromForm] ReportDto reportDto)
    {
        var result = await _reportService.UpdateExamReportStyleAsync(reportId, reportDto);
        return Ok(result);
    }

    [HttpGet("/api/report/{reportId}/get-study-base-info")]
    public async Task<IActionResult> GetStudyBaseInfo(Guid reportId)
    {
        var report = await _reportRepository.GetAsync(reportId);
        var exam = report.Exam;
        string GetAge()
        {
            if (exam.AgeValue.HasValue)
            {
                var ageUnit = exam.AgeUnit switch
                {
                    AgeUnit.Year => "Y",
                    AgeUnit.Month => "M",
                    AgeUnit.Day => "D",
                    AgeUnit.Hour => "H",
                    _ => "Y"
                };
                return $"{exam.AgeValue:000}{ageUnit}";
            }
            return string.Empty;
        }
        return Ok(new
        {
            Success = true,
            Data = new
            {
                Id = exam.Id.ToString(),
                ReportId = report.Id.ToString(),
                StudyUID = exam.StudyInstanceUid,
                PatientName = exam.Patient.Name,
                DeviceTypeCode = exam.DeviceType.Code,
                exam.DeviceType.Modality,
                exam.Patient.PatientId,
                exam.AccessionNumber,
                Date = exam.CreationTime,
                Age = GetAge(),
                Sex = exam.Patient.Sex switch
                {
                    PatientSex.Male => "M",
                    PatientSex.Female => "F",
                    _ => "O"
                },
            }
        });
    }
    [AllowAnonymous]
    [HttpPost("api/report/get-report-pdf-files")]
    public async Task<IActionResult> GetReportPdfFiles(IList<Guid> examIds)
    {
        var result = await _reportService.GetPdfFileAsync(examIds, ReportStyleType.Report);
        return Ok(result);
    }
    [HttpPost("api/report/remake-report-pdf-files")]
    public async Task<IActionResult> RemakeReportPdfFiles(IList<Guid> examIds)
    {
        var result = await _reportService.GeneratePdfFileAsync(examIds, ReportStyleType.Report);
        return Ok(result);
    }
    [HttpPost("api/report/get-temp-report-pdf-files")]
    public async Task<IActionResult> GetTempReportPdfFiles(IList<Guid> examIds)
    {
        var result = await _reportService.GetPdfFileAsync(examIds, ReportStyleType.TempReport);
        return Ok(result);
    }

    [HttpPost("api/report/give-up-write-report")]
    public async Task<IActionResult> GiveUpWriteReport(Guid reportId)
    {
        var result = await _reportService.GiveUpWriteReportAsync(reportId);
        return Ok(result);
    }

    [HttpPost("api/report/transter")]
    public async Task<IActionResult> TransferReport([FromBody] WorkflowInput input)
    {
        var result = await _reportService.TransferReportAsync(input, "/api/report/transter");
        return Ok(result);
    }

    // 拆分
    [HttpPost("api/report/disassemble")]
    public async Task<IActionResult> Disassemble([FromForm] Guid examId, [FromForm] List<Guid> examItemIds)
    {
        var result = await _reportService.DisassembleAsync(examId, examItemIds);
        return Ok(result);
    }

    [HttpPost("api/report/verify-user")]
    public async Task<IActionResult> VerifyUser([FromBody] WorkflowInput input)
    {
        var result = await _reportService.VerifyUserAsync(input, "/api/report/verify-user");
        return Ok(result);
    }

    [HttpPost("api/report/export")]
    public async Task<IActionResult> Export([FromBody] DataGridRequest request)
    {
        var result = await _reportService.ExportAsync(request);
        return Ok(result);
    }

    
    [HttpGet("api/report/image-quality-options")]
    public async Task<IActionResult> GetImageQualityOptions(Guid reportId) 
    {
        Report report = await _reportRepository.GetAsync(reportId);
        var qulityList = await _imageQualityRepository.GetListAsync(e => e.Department.Oid == _currentUserOrganization.DepartmentId && e.DeviceType == report.Exam.DeviceType&&e.IsActive);
        if (qulityList.Count > 0)
        {
            var result = qulityList.OrderBy(e => e.Order).ToList().Select(e => new { label = e.Name, value = e.Oid });
            return Ok(result);
        }
        else
        { 
            return Ok(null);
        }
    }

}
